package com.ruoyi.web.controller.client;


import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.GetUserId;
import com.ruoyi.common.enums.OperatorType;
import com.ruoyi.common.enums.RequestType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.responseBodyJson.JSON;
import com.ruoyi.framework.timetaskuntil.ApplicationContextUtil;
import com.ruoyi.framework.web.domain.server.Sys;
import com.ruoyi.yf.domain.YfInterface;
import com.ruoyi.yf.domain.YfTag;
import com.ruoyi.yf.domain.mobile.ResponseData;
import com.ruoyi.yf.service.IYfDeptService;
import com.ruoyi.yf.service.IYfInterfaceService;
import com.ruoyi.yf.service.IYfTagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * 接口 - 医废数据提交
 * 79164146-63b6-4742-8bbe-4f949095a6a7
 */
@RestController
@RequestMapping("/client/yfdata")
@Component
public class SubmitYFDataController extends BaseController {

    @Autowired
    private IYfTagService yfTagService;

    @Autowired
    private IYfInterfaceService yfInterfaceService;

    public static List<YfTag> yfTagList = new ArrayList<>();

    public static final Long SJZWJWID = 101L;


    // 未提交的医废数据提交到石家庄卫健委服务器
    //db825273-9bbe-4b50-93c2-c06e2d608e00
    @RequestMapping("/submitYFDataToSJZWJW")
//    @PostConstruct
    @ResponseBody
    @JSON(type = YfTag.class, include = "codeid,hospitalId,stagingId,bag,outBag,weight,outWeight,trashStatus,trashType," +
            "sourceDeptId,sourceDeptName,standardDeptCode,collectUserId,collectUserName,collectUpdateDate," +
            "intoUserId,intoUserName,intoDate,outUserId,outUserName,outDate,delFlag")
    public ResponseData submitYFDataToSJZWJW() {

        yfTagService = (IYfTagService) ApplicationContextUtil.getBean("yfTagService");
        yfInterfaceService = (IYfInterfaceService) ApplicationContextUtil.getBean("yfInterfaceService");


        // 查询石家庄卫健委下所有的暂存点，更改暂存点填报时间
        try{
            List<Long> staginglist = yfTagService.getStagingIdsBySJZWJWID(SJZWJWID);
            if (staginglist == null || staginglist.isEmpty()) {
                return ResponseData.successY("未有暂存点需要更改填报时间");
            }
            System.out.println("   ======= 需要更改暂存点填报时间的暂存点数量： " + staginglist.size());
            HttpRequest.post( yfInterfaceService.selectYfInterfaceById(1001L).getAddress().trim() )
                    .body(new Gson().toJson(staginglist), "application/json").timeout(60000).execute();
        }catch (Exception e){
            System.out.println("   ======= 更改暂存点填报时间异常！ " );
        }



        // 查询石家庄卫健委下属的所有暂存点未提交的医废数据  石家庄卫健委id：101
        yfTagList.clear();
        List<YfTag> list = yfTagService.getNoSubmitYF(SJZWJWID);
        if (list == null || list.isEmpty()) {
            return ResponseData.successY("未有医废需要提交");
        }
        yfTagList.addAll( list );
        System.out.println("   ======= 需要提交的医废数量： " + yfTagList.size());

        // 查询地址    毫秒
        YfInterface yfInterface = yfInterfaceService.selectYfInterfaceById(1000L);
        if (yfInterface == null || StringUtils.isEmpty(yfInterface.getAddress())) {
            return ResponseData.failureN("未查询到提交地址");
        }

        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        String param = gson.toJson(yfTagList);

        System.out.println("   ======= 发送的json： " + param );

        HttpResponse httpResponse = HttpRequest.post(yfInterface.getAddress().trim())
                .body(param, "application/json").timeout(180000).execute();
        int status = httpResponse.getStatus();
        if (status == 200) {    // 请求成功
            String result = httpResponse.body();
            ResponseData resultdata = new Gson().fromJson(result,ResponseData.class);
            if( resultdata != null && !StringUtils.isEmpty(resultdata.getResultCode()) && resultdata.getResultCode().equals("Y") ){
                System.out.println("   ======= 提交成功的医废数量： " + yfTagList.size());
                // 根据提交的条码和状态更改update_status
                yfTagService.updateStatusYFBycodeidAndStatus(yfTagList);
                yfTagList.clear();
                return ResponseData.successY("提交成功");
            } else {
                if( yfTagList!= null && !yfTagList.isEmpty() ) {
                    yfTagList.clear();
                }
                return ResponseData.failureN("请求失败 - 返回值有误" );
            }

        } else {
            if( yfTagList!= null && !yfTagList.isEmpty() ) {
                yfTagList.clear();
            }
            return ResponseData.failureN("请求失败 - 错误码：" + status );
        }

    }



    // 石家庄卫健委服务器接收院端提交的医废
    //1b13321d-e5fc-4b40-9341-1367c0005c90
    @RequestMapping("/receiveYFData")
    @ResponseBody
    public ResponseData receiveYFData(@RequestBody(required = false) List<YfTag> yfTagList) {
        if (yfTagList == null || yfTagList.isEmpty()) {
            return ResponseData.failureN("未有医废数据提交");
        }

        yfTagService = (IYfTagService) ApplicationContextUtil.getBean("yfTagService");

        // 先根据id批量删除医废，再批量添加医废      deleteYFBycodeidAndStatus   insertDelYfTagList
        try{
            // 把胎盘转成病理性    6 -> 1     病理性： 1    感染性：3
            for (int i = 0; i < yfTagList.size(); i++) {
                if(yfTagList.get(i).getTrashType().equals("6")){
                    yfTagList.get(i).setTrashType("1");
                }
            }
            yfTagService.receiveYFData(yfTagList);
            return ResponseData.successY("接收成功");
        }catch (Exception e){
            return ResponseData.failureN("接收失败");
        }

    }



    // 石家庄卫健委服务器接收今日无医废暂存点ids
    //10661a8c-2b9a-4cad-9f7c-c75936039d8a
    @RequestMapping("/receiveNoYFStagingIds")
    @ResponseBody
    public ResponseData receiveNoYFStagingIds(@RequestBody(required = false) List<Long> staginglist) {
        if (staginglist == null || staginglist.isEmpty()) {
            return ResponseData.failureN("未有暂存点id提交");
        }

        yfTagService = (IYfTagService) ApplicationContextUtil.getBean("yfTagService");

        yfTagService.receiveNoYFStagingIds(staginglist);
        return ResponseData.successY("接收成功");

    }





}
